<?php

namespace App\Admin\Controllers;

use App\Models\Video;
use App\Models\Blogger;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Controllers\AdminController;
use App\Admin\Actions\NewsAction\VideoTranslate;
use App\Admin\Actions\NewsAction\NewsExamine;
use App\Admin\Actions\NewsAction\VideoShareToLinkedin;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use App\Admin\Actions\NewsAction\BriefCreate;


class VideosController extends AdminController
{
    protected $title = '视频列表';
    
    protected function grid()
    {
        $grid = new Grid(new Video());
	   
        $grid->model()->orderByDesc('id')->paginate(50);
	    $grid->disableExport();
	    $grid->column('blogger_id', '博主名称')->display(function () {
            return $this->blogger ?  $this->blogger->blogger_name : '';
        });
        $grid->column('title', '标题');
        $grid->column('title_en', '英文标题');
        $grid->column('brief', '是否有描述')->bool();
	    $grid->column('url', '视频链接');
        $grid->column('like', '点赞');
        $grid->column('collect', '收藏');
        $grid->column('is_examine', '是否审核')->bool();
	    $grid->column('release_at', '发布时间');

        $grid->disableRowSelector();
        $grid->disableExport();
        $this->gridActions($grid);
        $this->gridFilter($grid);
        return $grid;
    }
    
    protected function detail($id)
    {
        $show = new Show(Video::findOrFail($id));

        $show->field('title', '标题');
        $show->field('url', '视频外网连接'); 
       // $show->field('content', '中文内容');
        $show->content()->unescape()->as(function ($content) {
            
            return $content;
        });
        $show->field('brief', '中文摘要');

        $show->field('title_en', '英文标题');

        $show->brief_en('英文摘要')->unescape()->as(function ($brief_en) {
            
            return "<textarea style='width:1000px;height:240px'>".$brief_en."</textarea>";
        });
        $show->video_url('视频')->unescape()->as(function ($url) {
            if(!strstr($url,"http")){

                $url = "https://xbreaking.oss-cn-beijing.aliyuncs.com".$url;
            }
            return "<video width='320' height='240' controls src='{$url}'>
                          
                      </video>";
        });

         $show->translate_video_url('视频')->unescape()->as(function ($url) {
            if(!strstr($url,"http")){

                $url = "https://littleshop.oss-cn-beijing.aliyuncs.com/".$url;
            }
            return "<video width='320' height='240' controls src='{$url}'>
                          
                      </video>";
        });

        return $show;
    }

    protected function gridFilter(Grid $grid)
    {
        $grid->filter(function (Grid\Filter $filter) {
            $filter->expand();

            

            $filter->column(1/2, function (Grid\Filter $filter) {
                $filter->equal('blogger_id', '博主查询')->select(Blogger::all()->pluck('blogger_name', 'id'));
            });
             $filter->column(1/2, function (Grid\Filter $filter) {
                $filter->equal('type', '平台')->select(config('site.blogger_platform'));
            });
            
        });
    }
    
    protected function gridActions(Grid $grid)
    {
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            
            $actions->add(new NewsExamine());
            $actions->add(new VideoTranslate());
            $actions->add(new VideoShareToLinkedin());
            $actions->add(new BriefCreate());
        });
    }
    protected function form()
    {
        $form = new Form(new Video());
	    $form->text('title', '标题');
        $form->text('url', '视频连接');
	    $form->simditor('content', '中文内容');
        $form->textarea('brief', '中文摘要');
        $form->textarea('title_en', '英文标题');
        $form->textarea('brief_en', '英文摘要');
	    $form->display('video_url', '视频')->customFormat(function ($url) {
                if(!strstr($url,"http")){

                $url = "https://xbreaking.oss-cn-beijing.aliyuncs.com".$url;
            }
            return "<video width='320' height='240' controls src='{$url}'>
                          
                      </video>";
         });

         $form->display('translate_video_url', '翻译后视频链接')->customFormat(function ($url) {
              if(!strstr($url,"http")){

                $url = "https://littleshop.oss-cn-beijing.aliyuncs.com".$url;
            }
            return "<video width='320' height='240' controls src='{$url}'>
                          
                      </video>";
         });


       // $form->file('translate_video_url', '翻译后视频链接')->downloadable();
	   
         //$this->formSaving($form);
         $this->formSaved($form);
        return $form;
    }


    protected function formSaved(Form $form)
    {
        $form->saved(function (Form $form) {
            
            $model = $form->model();

            if(!$model->video_url){

                if(strstr($model->url,"douyin")){

                    if(strstr($model->url,"modal_id")){

                        $allUrl = explode("&",$model->url);

                        foreach($allUrl as $k=>$v){

                            if(strstr($v,"modal_id")){
                                $model->url = "https://www.douyin.com/video/".str_replace("modal_id=","",$v);
                            }
                             
                        }
                       
                    }

                   $apiUrl = "https://api.pearktrue.cn/api/video/douyin/?url=".$model->url;
                   $video = $this->curl($apiUrl);
                   $video = json_decode($video,true);
                    if(isset($video['code']) && $video['code']=="200"){


                        /*preg_match('/[0-9]+/', $model->url, $aid);
                        $aid = $aid[0];
                        $isVideoExists = Video::query()->where('bli_aid',$aid)->exists();

                        if($isVideoExists){
                             return back()->with(admin_error('该视频已存在！'));
                        }*/
                        $insertData = [
                            'aid' => 0,
                            'blogger_id' => 0,
                            'like' => $video['data']['like'],
                            'collect' => $video['data']['collect'],
                            'title' => $video['data']['title'],
                        ];
                      


                        $content = file_get_contents($video['data']['url']);

                        $newFileName = "/video/".Str::random(40) . '.mp4'; // 默认MP4格式
                        Storage::disk('ossnew')->put($newFileName, $content);

                        $insertData['video_url'] = Storage::disk('ossnew')->path($newFileName);

                        $model->update($insertData);
                    }else{
                         return back()->with(admin_error('无法识别该链接'));
                    }

                }elseif(strstr($model->url,"bilibili")){
                    $SESSDATA="02eca6d5%2C1759658193%2C4062e%2A41CjD7LUeo2T24vXtrx211w7wpEmuZlj7av1m3uuVHRKBl3zhQrzHFMdC461chG4v-0K0SVk1OeGVZYS1YX2o2TEEtU0lkVVhjNG1BdlVxWGRhUzN6aWlZODJxU08zNkdoNllvcXJUYk1PUFd1Ny0xcXNqRnFzUEJPMUZIM2o4MDMzblg5MG55Um53IIEC";
                   
                    $bvidArr = explode("/",$model->url);
                    $bvid = $bvidArr[4];
                    $apiUrl = "https://api.pearktrue.cn/api/bilibili/info.php?bvid=".$bvid;
                    $video = $this->curl($apiUrl);
                    $video = json_decode($video,true);

                     if(isset($video['code']) && $video['code']=="200"){

                        $insertData = [
                            'aid' => $video['data']['aid'],
                            'blogger_id' => 0,
                            'like' => $video['data']['like'],
                            'collect' => $video['data']['favorite'],
                            'title' => $video['data']['title'],
                        ];
                      


                        $apiVideoUrl = "https://api.pearktrue.cn/api/bilibili/parse.php?bvid=".$bvid."&sessdata=".$SESSDATA;
                        $videoUrl = $this->curl($apiVideoUrl);
                        $videoUrl = json_decode($videoUrl,true);

                        if(isset($videoUrl['code']) && $videoUrl['code']=="200"){

                           /*$content = file_get_contents($videoUrl['data']['videos'][0]['videourl']);

                            $newFileName = "/video/".Str::random(40) . '.mp4'; // 默认MP4格式
                            Storage::disk('ossnew')->put($newFileName, $content);*/

                            $insertData['video_url'] = Storage::disk('ossnew')->path($videoUrl['data']['videos'][0]['videourl']);
                        }    

                        $model->update($insertData);
                    }else{
                         return back()->with(admin_error('无法识别该链接'));
                    }


                }

            }
            
        });
    }

     private function curl($url, $header = null, $data = null)
    {

        if(!$header){
            $header = ["UIFID_TEMP=973a3fd64dcc46a3490fd9b60d4a8e663b34df4ccc4bbcf97643172fb712d8b0d491cf34a443d6a4fbe934bc69004bdb3e9df47e1b123c663c23737c005b25b1061efcc1f9107fba3dda20da588d86f7; fpk1=U2FsdGVkX1892/Wewm2kl6QVgTdlTHWGz6t8W+ZOkA69Jv4vWXwBpVX3JqwPDviosbcL5SPo+W9LLr6zTnW28g==; fpk2=362d7fe3d8b2581bffa359f0eeda7106; xgplayer_user_id=157989025067; UIFID=973a3fd64dcc46a3490fd9b60d4a8e663b34df4ccc4bbcf97643172fb712d8b07d4f8b046eeb4ed33f08610a69a116e514de9239ca9246f41b28e699eff8491ac7da6bffadba9601fda08c85eee06c4b441f1ad1438af03aa4caa6259f8e0a08253758d130879bb691eb4f6dfe163f181960b92bdcf868a85490dba916734044ffa8b0a1c4f77a2b38dde92e74ad508c534e8e6e7cebea21ef1a920a422007f0; live_use_vvc=%22false%22; d_ticket=3a5d57736db2b89e74b7c55f919b6325c2f65; store-region=cn-bj; store-region-src=uid; hevc_supported=true; SelfTabRedDotControl=%5B%5D; my_rd=2; xgplayer_device_id=57310421561; SEARCH_RESULT_LIST_TYPE=%22single%22; s_v_web_id=verify_m771gc61_0jSW9NQ4_KgFs_4s3I_B7BK_lPKb9DG3xRAM; passport_csrf_token=91b71805b01f95c6fc43c6fe4df9cc14; passport_csrf_token_default=91b71805b01f95c6fc43c6fe4df9cc14; __security_mc_1_s_sdk_crypt_sdk=c253abbb-4160-97c2; __security_mc_1_s_sdk_cert_key=288a82d1-4fd0-a26b; bd_ticket_guard_client_web_domain=2; __security_mc_1_s_sdk_sign_data_key_login=c58d88db-4448-9178; passport_assist_user=Cjx72BeU7EN3LC11ynTi_ZpvNGDghzh22X6Bn-2sBOa4uGiolX8Fd-saD69diwuiRVj4SqKB0x2Yz0QgqZQaSgo8KoTge4SGY7esCLASJtpQJZxBaE0qtIVRR3pSl2aGy7pX5XtO6JwMOZqKK5uVhS90kKQDvOOa4fI7WAX6EO2c6g0Yia_WVCABIgEDJM5f1Q%3D%3D; n_mh=Gi-y0Kudo-jhDK-HkZtaRYg-sabfJtqDw2U9-1uyN0o; sso_uid_tt=34727fd05c7787fc639424a1f8e21560; sso_uid_tt_ss=34727fd05c7787fc639424a1f8e21560; toutiao_sso_user=897957183084ffac9b1747be8b0396ed; toutiao_sso_user_ss=897957183084ffac9b1747be8b0396ed; sid_ucp_sso_v1=1.0.0-KDA5ZThhMzQ3NTZjMDk1YzA1MjNmYmQzYjU0ZmQwOTAwMzA3NmIzYWEKHwiDmv_olwIQ_bLmvQYY7zEgDDCy14vQBTgFQPsHSAYaAmxxIiA4OTc5NTcxODMwODRmZmFjOWIxNzQ3YmU4YjAzOTZlZA; ssid_ucp_sso_v1=1.0.0-KDA5ZThhMzQ3NTZjMDk1YzA1MjNmYmQzYjU0ZmQwOTAwMzA3NmIzYWEKHwiDmv_olwIQ_bLmvQYY7zEgDDCy14vQBTgFQPsHSAYaAmxxIiA4OTc5NTcxODMwODRmZmFjOWIxNzQ3YmU4YjAzOTZlZA; __security_mc_1_s_sdk_sign_data_key_sso=8a7bda19-46f7-b3e1; login_time=1740216701995; uid_tt=5c32dfc9fa3c845d7a420bc0b371fc1d; uid_tt_ss=5c32dfc9fa3c845d7a420bc0b371fc1d; sid_tt=b0cd71c10a5d6d39a975a43c5a5245d2; sessionid=b0cd71c10a5d6d39a975a43c5a5245d2; sessionid_ss=b0cd71c10a5d6d39a975a43c5a5245d2; is_staff_user=false; _bd_ticket_crypt_doamin=2; _bd_ticket_crypt_cookie=827cd784407291a7559caf33e9907c6e; __security_mc_1_s_sdk_sign_data_key_web_protect=28cbe375-4ff8-b05a; __security_server_data_status=1; dy_swidth=1920; dy_sheight=1080; is_dash_user=1; sid_guard=b0cd71c10a5d6d39a975a43c5a5245d2%7C1743165824%7C5184000%7CTue%2C+27-May-2025+12%3A43%3A44+GMT; sid_ucp_v1=1.0.0-KDk5ZGNhYWUyZTIxYTEyM2VlOTUxNDE2ZWJiYjM0NWIwZTUyZTA0YjQKGQiDmv_olwIQgLOavwYY7zEgDDgFQPsHSAQaAmhsIiBiMGNkNzFjMTBhNWQ2ZDM5YTk3NWE0M2M1YTUyNDVkMg; ssid_ucp_v1=1.0.0-KDk5ZGNhYWUyZTIxYTEyM2VlOTUxNDE2ZWJiYjM0NWIwZTUyZTA0YjQKGQiDmv_olwIQgLOavwYY7zEgDDgFQPsHSAQaAmhsIiBiMGNkNzFjMTBhNWQ2ZDM5YTk3NWE0M2M1YTUyNDVkMg; __live_version__=%221.1.3.20%22; ttwid=1%7CxFxVdAmTYIeW_qLHss8eWb8EXB_gwQb7rxjf8rKVVAA%7C1743578780%7Cfb11f114acc6cdfc5125d19d16f0b13970f5ec5e85d645803f84c5c24a1c4d1c; WallpaperGuide=%7B%22showTime%22%3A1743589725922%2C%22closeTime%22%3A0%2C%22showCount%22%3A2%2C%22cursor1%22%3A35%2C%22cursor2%22%3A10%2C%22hoverTime%22%3A1743240290180%7D; volume_info=%7B%22isUserMute%22%3Afalse%2C%22isMute%22%3Atrue%2C%22volume%22%3A0.153%7D; __ac_nonce=067f4c9a7003554d799f; __ac_signature=_02B4Z6wo00f01Ax3cWAAAIDAO1O1PtOkpkQMV3XAAGTv9e; douyin.com; xg_device_score=7.601307259398018; device_web_cpu_core=12; device_web_memory_size=8; architecture=amd64; stream_recommend_feed_params=%22%7B%5C%22cookie_enabled%5C%22%3Atrue%2C%5C%22screen_width%5C%22%3A1920%2C%5C%22screen_height%5C%22%3A1080%2C%5C%22browser_online%5C%22%3Atrue%2C%5C%22cpu_core_num%5C%22%3A12%2C%5C%22device_memory%5C%22%3A8%2C%5C%22downlink%5C%22%3A10%2C%5C%22effective_type%5C%22%3A%5C%224g%5C%22%2C%5C%22round_trip_time%5C%22%3A0%7D%22; FOLLOW_LIVE_POINT_INFO=%22MS4wLjABAAAANbSMg0p-AoI4HvZJMJgLcrN2BKNyAZ2cg6YuFOIJWTE%2F1744128000000%2F0%2F1744095659005%2F0%22; bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWl0ZXJhdGlvbi12ZXJzaW9uIjoxLCJiZC10aWNrZXQtZ3VhcmQtcmVlLXB1YmxpYy1rZXkiOiJCRENaUkVUSjhNZWtnK0pnUnZxRFhoYnRlMzdOVXZNU01qRDBhSkFPaG5WQUN6MHBBU2JMaVZPM1JmRHRoZHgxS3psTThFUUFORElpWjRsSUVLYml3Z3M9IiwiYmQtdGlja2V0LWd1YXJkLXdlYi12ZXJzaW9uIjoyfQ%3D%3D; home_can_add_dy_2_desktop=%221%22; strategyABtestKey=%221744095659.897%22; biz_trace_id=7f69076f; publish_badge_show_info=%220%2C0%2C0%2C1744095663626%22; odin_tt=9cdc5d3e34f04660d0fb43a7e30592439cc21df6995d6c5f155c832e14536f15a0b23d6e03e1e829eb5f0dbf93c1654a; SelectedFeedCache=3; download_guide=%221%2F20250408%2F0%22; IsDouyinActive=false; passport_fe_beating_status=false"];

        }
        
        $con = curl_init((string)$url);
        curl_setopt($con, CURLOPT_HEADER, false);
        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($con, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($con, CURLOPT_AUTOREFERER, 1);
        if (isset($header)) {
            curl_setopt($con, CURLOPT_HTTPHEADER, $header);
        }
        if (isset($data)) {
            curl_setopt($con, CURLOPT_POST, true);
            curl_setopt($con, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($con, CURLOPT_TIMEOUT, 5000);
        $result = curl_exec($con);
        return $result;
    }
}
